<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="素材名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入素材名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="素材类型" prop="materialType">
        <el-select v-model="queryParams.materialType" placeholder="请选择素材类型" clearable>
          <el-option
            v-for="dict in dict.type.mips_material_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文件原始名" prop="fileOriginal">
        <el-input
          v-model="queryParams.fileOriginal"
          placeholder="请输入文件原始名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="auditStatus">
        <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable>
          <el-option
            v-for="dict in dict.type.mips_audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['publish:mipsMaterialFiles:add']"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['publish:mipsMaterialFiles:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['publish:mipsMaterialFiles:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="mipsMaterialFilesList" @selection-change="handleSelectionChange" :row-class-name="tableRowClassName" @cell-click="tabClick">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="素材主键" align="center" prop="materialId" v-if="false" />
      <el-table-column label="素材名称" align="center" prop="materialName">
        <template slot-scope="scope">
          <span v-if="scope.row.index === tabClickIndex && tabClickLabel === '素材名称'">
            <div style="display: flex">
            <el-input tabindex="1" v-model="scope.row.materialName"  maxlength="20" placeholder="请输入素材名称" size="mini" @blur="inputBlur(scope.row)" />
            <el-button tabindex="0" size="mini" @click="updateMaterialName(scope.row)">更新</el-button>
              </div>
          </span>
          <span v-else>{{ scope.row.materialName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="素材类型" align="center" prop="materialType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mips_material_type" :value="scope.row.materialType"/>
        </template>
      </el-table-column>
      <el-table-column label="文件原始名" align="center" prop="fileOriginal" />
      <el-table-column label="文件扩展名" align="center" prop="fileExtension" />
      <el-table-column label="文件大小" align="center" prop="fileSize" :formatter="fileSizefmt" />
      <el-table-column label="预览路径" align="center" prop="filePreview" v-if="false"/>
      <el-table-column label="素材路径" align="center" prop="filePath" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.materialType == 1" :src="scope.row.filePath" :width="50" :height="50"/>
          <video v-else :src="'http://'+GLOBAL.backServerIp + ':' + GLOBAL.backServerPort + scope.row.filePath" :height="50" controls></video>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="auditStatus" v-if="false">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mips_audit_status" :value="scope.row.auditStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-hasPermi="['publish:mipsMaterialFiles:edit']"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['publish:mipsMaterialFiles:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改素材管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="">
          <UploadFiles v-model="form.filePath" @uploadSuccess="uploadSuccess" :fileType="fileType" :fileSize="fileSize" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMipsMaterialFiles, getMipsMaterialFiles, delMipsMaterialFiles, addMipsMaterialFiles, updateMipsMaterialFiles } from "@/api/publish/mipsMaterialFiles";

import UploadFiles from "./uploadFiles";

export default {
  name: "MipsMaterialFiles",
  dicts: ['mips_material_type', 'mips_audit_status'],
  components: {
    UploadFiles
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 素材管理表格数据
      mipsMaterialFilesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: null,
        materialType: null,
        fileOriginal: null,
        deptId: null,
        auditStatus: null,
      },
      // 表单参数
      form: {},
      formArr:[],
      // 表单校验
      rules: {
        filePath: [
          { required: true, message: "素材路径不能为空", trigger: "blur" }
        ],
      },
      fileType:['jpg', 'png', 'jpeg', 'mp4', 'avi', 'mp3', 'wav', 'flv', 'mov', 'wmv'],
      // fileType:null,
      fileSize: 1024,
      tabClickIndex:'',
      tabClickLabel:'',
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询素材管理列表 */
    getList() {
      this.loading = true;
      listMipsMaterialFiles(this.queryParams).then(response => {
        this.mipsMaterialFilesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialId: null,
        materialName: null,
        materialType: null,
        fileOriginal: null,
        fileExtension: null,
        fileSize: null,
        filePreview: null,
        filePath: null,
        deptId: null,
        auditStatus: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加素材";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const materialId = row.materialId || this.ids
      getMipsMaterialFiles(materialId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改素材";
      });
    },
    /** 提交按钮 */
    submitForm() {
      const _this = this;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.materialId != null) {
            updateMipsMaterialFiles(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {

            addMipsMaterialFiles(_this.formArr).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialIds = row.materialId || this.ids;
      this.$modal.confirm('是否确认删除素材编号为"' + materialIds + '"的数据项？').then(function() {
        return delMipsMaterialFiles(materialIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('publish/mipsMaterialFiles/export', {
        ...this.queryParams
      }, `mipsMaterialFiles_${new Date().getTime()}.xlsx`)
    },
    uploadSuccess(fileList) {

      this.formArr = [];
      for (var x = 0; x < fileList.length; x++) {
        let file = fileList[x];
        var obj = new Object();
        obj.materialName = file.originalFilename;
        obj.fileOriginal = file.originalFilename;
        obj.filePath = file.fileName;
        obj.materialType = file.mediaType;
        obj.fileExtension = file.fileExtension;
        obj.fileSize = file.fileSize;
        this.formArr.push(obj);
      }
    },
    fileSizefmt(row) {
      let bytes = row.fileSize;
      if (bytes < 1024) {
        return bytes + ' bytes';
      } else if (bytes < 1048576) {
        return (bytes / 1024).toFixed(2) + ' KB';
      } else if (bytes < 1073741824) {
        return (bytes / 1048576).toFixed(2) + ' MB';
      } else {
        return (bytes / 1073741824).toFixed(2) + ' GB';
      }
    },
    //设置表格行索引
    tableRowClassName ({ row, rowIndex }) {
      row.index = rowIndex// 把每一行的索引放进row
    },
    // tabClick row 当前行 column 当前列
    tabClick (row, column, cell, event) {
      switch (column.label) {
        case '素材名称':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
        // console.log('tabClick:'+this.tabClickIndex+'---'+this.tabClickLabel)
        case '备注':
          this.tabClickIndex = row.index
          this.tabClickLabel = column.label
          // console.log('tabClick:'+this.tabClickIndex+'---'+this.tabClickLabel)
          break
        default: return
      }
    },
    // 失去焦点初始化
    inputBlur (row) {
      // console.log('row', row)
      // this.tabClickIndex = -1
      // this.tabClickLabel = ''
      this.updateMaterialName(row);
      // console.log("失焦事件："+this.tabClickIndex)
    },
    updateMaterialName(row) {
      updateMipsMaterialFiles(row).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.tabClickIndex = -1
        this.tabClickLabel = ''
        this.open = false;
        this.getList();
      });
    }

  }
};
</script>
